package cn.edu.zstu.qingzhu.qingzhushop.service.impl;

import cn.edu.zstu.qingzhu.qingzhushop.properties.EmailProperties;
import cn.edu.zstu.qingzhu.qingzhushop.service.IEmailService;
import javafx.util.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * @Author ShenTuZhiGang
 * @Version 1.0.0
 * @Date 2020-02-15 21:31
 */
@Service
public class EmailServiceImpl implements IEmailService {
    @Autowired
    private EmailProperties emailProperties;

    @Autowired
    private JavaMailSender mailSender;

    /**
     * 用来发送模版邮件
     */
    @Autowired
    private TemplateEngine templateEngine;


    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(emailProperties.getEmailFrom());
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }

    @Override
    public void sendAttachmentsMail(String to, String subject, String content, List<Pair<String, File>> attachments) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(emailProperties.getEmailFrom());
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            if (attachments != null) {
                for (Pair<String, File> attachment : attachments) {
                    FileSystemResource file = new FileSystemResource(attachment.getValue());
                    helper.addAttachment(attachment.getKey(), file);
                }
            }
            mailSender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void sendTemplateMail(String template, String to, String subject, Map<String, Object> content, List<Pair<String, File>> attachments) {
        Context context = new Context();
        context.setVariables(content);
        String emailContent = templateEngine.process(template, context);
        sendAttachmentsMail(to, subject, emailContent, attachments);
    }
}
